﻿using System;
using System.IO;
using System.Xml;
using Microsoft.Deployment.WindowsInstaller;

namespace UnigyLyncAddinSetupCustomActions
{
	public class ReadXmlConfigCustomAction
	{
		private static readonly string SERVER_IP_PROPERTY = "SERVER_IP";
		private static readonly string SERVER_PORT_PROPERTY = "SERVER_PORT";
		private static readonly string SERVER_SECURE_CONNECTION_PROPERTY = "SERVER_SECURE_CONNECTION";
		private static readonly string CONFIG_FILENAME_PROPERTY = "CONFIG_FILENAME";
		private static readonly string CONFIG_NODE_NAME = "appSettings";
		private static readonly string CONFIG_SUBNODE_NAME = "add";
		private const string IpAttrName = "SERVERIP";
		private const string PortAttrName = "SERVERPORT";
		private const string SecureConnectionAttrName = "ISSECURECONNECTION";

		[CustomAction]
		public static ActionResult ReadXmlConfig(Session session)
		{
			session.Log("Begin ReadXmlConfig");
			//MessageBox.Show("Begin ReadXmlConfig");
			var xmlFile = session[CONFIG_FILENAME_PROPERTY];
			session.Log("ReadXmlConfig - XmlConfig 1: {0}. Exists: {1}", xmlFile, File.Exists(xmlFile));
			
			if (File.Exists(xmlFile))
			{
				session.Log("XmlConfig file exists");
				using (var reader = XmlReader.Create(session[CONFIG_FILENAME_PROPERTY],
													 new XmlReaderSettings
														 {
															 IgnoreComments = true,
															 IgnoreWhitespace = true
														 }))
				{
					while (reader.Read())
					{
						if (reader.NodeType == XmlNodeType.Element &&
							reader.Name == CONFIG_NODE_NAME &&
							!reader.IsEmptyElement)
						{
							while (reader.Read() &&
								   reader.Name == CONFIG_SUBNODE_NAME &&
								   reader.HasAttributes)
							{
								var key = reader.GetAttribute("key").ToUpperInvariant();
								switch (key)
								{
									case IpAttrName:
										session[SERVER_IP_PROPERTY] = reader.GetAttribute("value");
										break;
									case PortAttrName:
										session[SERVER_PORT_PROPERTY] = reader.GetAttribute("value");
										break;
									case SecureConnectionAttrName:
										session[SERVER_SECURE_CONNECTION_PROPERTY] = string.Equals("true", reader.GetAttribute("value"), StringComparison.InvariantCultureIgnoreCase) ? "1" : string.Empty;
										session.Log("ReadXmlConfig - Attribute: {0}",
											session[SERVER_SECURE_CONNECTION_PROPERTY]);
										break;
								}
							}
						}
					}
				}
			}

			session.Log("ReadXmlConfig - Result: {0}: {1}. {2}: {3}. {4}: {5}",
										  SERVER_IP_PROPERTY,
										  session[SERVER_IP_PROPERTY],
										  SERVER_PORT_PROPERTY,
										  session[SERVER_PORT_PROPERTY],
										  SERVER_SECURE_CONNECTION_PROPERTY,
										  session[SERVER_SECURE_CONNECTION_PROPERTY]);

			return ActionResult.Success;
		}
	}
}